package utils

import (
	"log"
	"os/exec"
	"runtime"
	"time"
)

// openBrowser 自动打开浏览器访问指定URL
func openBrowser(url string) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start", url}
	case "darwin": // macOS
		cmd = "open"
		args = []string{url}
	default: // linux, freebsd, etc.
		cmd = "xdg-open"
		args = []string{url}
	}

	return exec.Command(cmd, args...).Start()
}

// 带重试机制的打开浏览器
func openBrowserWithRetry(url string, maxRetries int, delaySeconds int) {
	time.Sleep(time.Duration(delaySeconds) * time.Second)

	for i := 0; i < maxRetries; i++ {
		err := openBrowser(url)
		if err == nil {
			log.Printf("✅ 浏览器已自动打开: %s", url)
			return
		}

		if i < maxRetries-1 {
			log.Printf("⚠️  尝试打开浏览器失败 (%d/%d), 1秒后重试...", i+1, maxRetries)
			time.Sleep(1 * time.Second)
		}
	}

	log.Printf("❌ 无法自动打开浏览器，请手动访问: %s", url)
}
